package com.xdap.pg.exam.service;

import com.alibaba.fastjson.JSON;
import com.definesys.mpaas.query.MpaasQuery;
import com.xdap.common.constant.DatasourceConstant;
import com.xdap.pg.exam.dto.ExamQuestionDto;
import com.xdap.pg.exam.entity.*;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DataService {

    @Resource RuntimeDatasourceService runtimeDatasourceService;
    @Resource RuntimeAppContextService runtimeAppContextService;

    public List<ItemBank> getItemBank(final String siteId, final List<String> areas, final String versionId) {
        Map<String,String> areaMap = Optional.ofNullable(getAllArea()).orElseGet(ArrayList::new).stream().collect(Collectors.toMap(Area::getAreaName, Area::getId, (key1, key2) -> key1));
        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(DatasourceConstant.XDAP_MYSQL_PREFIX + runtimeAppContextService.getCurrentTenantId()).table("item_bank");
        mpaasQuery.eq("item_version", versionId);
        mpaasQuery.eq("item_Site", siteId);
        mpaasQuery.eq("item_isfinished", "no");

        if (Objects.nonNull(areas)) {
            if (areas.size() == 1) {
                final String areaId = areaMap.get(areas.get(0));
                mpaasQuery.like("item_area", areaId);
            } else {
                mpaasQuery.conjuctionAnd();
                mpaasQuery.groupBegin();
                for(String area : areas) {
                    final String areaId = areaMap.get(area);
                    mpaasQuery.like("item_area", areaId);
                    mpaasQuery.conjuctionOr();
                }
                mpaasQuery.groupEnd();
            }
        }

        mpaasQuery.select("id","Code","no","item_type","item_frequency","item_Site","item_group","item_area","item_check_item","item_notes","item_isfinished","item_version");
        Map<String,String> paperItemMap = Optional.ofNullable(getAllPapaerItem(siteId, versionId)).orElseGet(ArrayList::new).stream()
                .collect(Collectors.toMap(PaperItem::getPaperItemCode,PaperItem::getPaperItemCode, (key1, key2) -> key1));
        List<ItemBank> itemBanks = mpaasQuery.doQuery(ItemBank.class);
        log.info("查询个数：itemBanks:{}" , itemBanks.size());
        List<ItemBank> itemBankList = Optional.ofNullable(itemBanks).orElseGet(ArrayList::new).stream()
                .filter(itemBank -> Objects.isNull(paperItemMap.get(itemBank.getId())) || StringUtils.isBlank(paperItemMap.get(itemBank.getId()))).collect(Collectors.toList());
        log.info("查询个数：itemBankList:{}" , itemBankList.size());
        return itemBankList;
    }

    public List<ItemBank> getAllItemBanks(final String siteId, final String versionId) {
        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(DatasourceConstant.XDAP_MYSQL_PREFIX + runtimeAppContextService.getCurrentTenantId()).table("item_bank");
        mpaasQuery.eq("item_version", versionId);
        mpaasQuery.eq("item_Site", siteId);
        mpaasQuery.select("id","Code","no","item_type","item_frequency","item_Site","item_group","item_area","item_check_item","item_notes","item_isfinished","item_version");
        List<ItemBank> itemBanks = mpaasQuery.doQuery(ItemBank.class);
        Optional.ofNullable(itemBanks).orElseGet(ArrayList::new).forEach(itemBank -> {
            itemBank.setItemType(itemBank.getItemType().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemGroup(itemBank.getItemGroup().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemFrequency(StringUtils.isNotBlank(itemBank.getItemFrequency()) ? itemBank.getItemFrequency().replace("\\","").replace("[\"","").replace("\"]","") : StringUtils.EMPTY);
            itemBank.setItemIsfinished(itemBank.getItemIsfinished().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemSite(itemBank.getItemSite().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemArea(itemBank.getItemArea().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemVersion(itemBank.getItemVersion().replace("\\","").replace("[\"","").replace("\"]",""));
        });
        return itemBanks;
    }

    public List<ItemBank> getYesItemBanks(final String siteId, final String versionId) {
        MpaasQuery mpaasQuery = runtimeDatasourceService.buildTenantMpaasQuery(DatasourceConstant.XDAP_MYSQL_PREFIX + runtimeAppContextService.getCurrentTenantId()).table("item_bank");
        mpaasQuery.eq("item_version", versionId);
        mpaasQuery.eq("item_Site", siteId);
        mpaasQuery.eq("item_isfinished", "yes");
        mpaasQuery.select("id","Code","no","item_type","item_frequency","item_Site","item_group","item_area","item_check_item","item_notes","item_isfinished","item_version");
        List<ItemBank> itemBanks = mpaasQuery.doQuery(ItemBank.class);
        Optional.ofNullable(itemBanks).orElseGet(ArrayList::new).forEach(itemBank -> {
            itemBank.setItemType(itemBank.getItemType().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemGroup(itemBank.getItemGroup().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemFrequency(StringUtils.isNotBlank(itemBank.getItemFrequency()) ? itemBank.getItemFrequency().replace("\\","").replace("[\"","").replace("\"]","") : StringUtils.EMPTY);
            itemBank.setItemIsfinished(itemBank.getItemIsfinished().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemSite(itemBank.getItemSite().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemArea(itemBank.getItemArea().replace("\\","").replace("[\"","").replace("\"]",""));
            itemBank.setItemVersion(itemBank.getItemVersion().replace("\\","").replace("[\"","").replace("\"]",""));
        });
        return itemBanks;
    }

    public String getVersionSelectId (final ExamQuestionDto examQuestionDto) {
        Map<String,String> versionMap = Optional.ofNullable(getAllQuestionVersion())
                .orElseGet(ArrayList::new)
                .stream()
                .collect(Collectors.toMap(QuestionVersion::getVersionStr, QuestionVersion::getId, (key1, key2) -> key1));
        //version 单选
        final String version = examQuestionDto.getVersion();
        return "[\"" + versionMap.get(version) + "\"]";
    }

    public String getSiteNameSelectId(final ExamQuestionDto examQuestionDto) {
        Map<String,String> siteMap = Optional.ofNullable(getAllSite())
                .orElseGet(ArrayList::new)
                .stream()
                .collect(Collectors.toMap(Site::getSiteName, Site::getId, (key1, key2) -> key1));
        //siteName 单选
        final String siteName = examQuestionDto.getSiteName();
        return "[\"" + siteMap.get(siteName) + "\"]";
    }


    public List<PaperItem> getAllPapaerItem(final String paperItemSite, final String paperItemVersion) {
        List<PaperItem> paperItems = runtimeDatasourceService.buildTenantMpaasQuery(DatasourceConstant.XDAP_MYSQL_PREFIX + runtimeAppContextService.getCurrentTenantId())
                .select("id","answer_item_list_Code","answer_item_list_Type")
                .ne("answer_item_list_results","[\"cant\"]")
                .isNotNull("answer_item_list_Code")
                .isNotNull("answer_item_list_Type")
                .eq("answer_item_list_site_name",paperItemSite)
                .eq("answer_item_list_Code_version", paperItemVersion)
                .conjuctionOr()
                .and()
                .isNull("answer_item_list_results")
                .isNotNull("answer_item_list_Code")
                .isNotNull("answer_item_list_Type")
                .eq("answer_item_list_site_name",paperItemSite)
                .eq("answer_item_list_Code_version", paperItemVersion)
                .doQuery(PaperItem.class);
        Optional.ofNullable(paperItems).orElseGet(ArrayList::new).stream().forEach(paperItem -> {
            paperItem.setPaperItemCode(paperItem.getPaperItemCode().replace("\\","").replace("[\"","").replace("\"]",""));
            paperItem.setPaperItemType(paperItem.getPaperItemType().replace("\\","").replace("[\"","").replace("\"]",""));
        });
        log.info("查询个数：paperItems :{}", paperItems.size());
        return paperItems;
    }

    /**
     * 查询所有的site
     * @return
     */
    private List<Site> getAllSite() {
        return runtimeDatasourceService.buildTenantMpaasQuery(DatasourceConstant.XDAP_MYSQL_PREFIX + runtimeAppContextService.getCurrentTenantId()).select("id","Site_Name").doQuery(Site.class);
    }

    /**
     * 查询所有的 Area
     * @return
     */
    private List<Area> getAllArea() {
        return runtimeDatasourceService.buildTenantMpaasQuery(DatasourceConstant.XDAP_MYSQL_PREFIX + runtimeAppContextService.getCurrentTenantId()).select("id","Area_Name").doQuery(Area.class);
    }

    /**
     * 查询所有的 ItemBankVersion
     * @return
     */
    public List<QuestionVersion> getAllQuestionVersion() {
        List<QuestionVersion> questionVersions =
                runtimeDatasourceService.buildTenantMpaasQuery(DatasourceConstant.XDAP_MYSQL_PREFIX + runtimeAppContextService.getCurrentTenantId())
                        .select("id", "version_str")
                        .doQuery(QuestionVersion.class);
        log.info("查询所有的ItemBankVersion:{}", JSON.toJSONString(questionVersions));
        return questionVersions;
    }


}
